package jface.solutions.util;

import jface.data.Person;
import jface.data.Person.Gender;

import org.eclipse.jface.viewers.CellEditor;
import org.eclipse.jface.viewers.ComboBoxCellEditor;
import org.eclipse.jface.viewers.EditingSupport;
import org.eclipse.jface.viewers.TableViewer;

public class GenderEditingSupportExercise extends EditingSupport {
	private static final String[] options = new String[]{"male", "female", "unknown"};
	private TableViewer viewer;

	public GenderEditingSupportExercise(TableViewer viewer) {
		super(viewer);
		this.viewer = viewer;
	}

	protected CellEditor getCellEditor(Object element) {
		return new ComboBoxCellEditor(viewer.getTable(), options);
	}

	protected boolean canEdit(Object element) {
		return true;
	}

	protected Object getValue(Object element) {
		Person person = (Person) element;
		switch (person.getGender()) {
			case male:
				return 0;
			case female:
				return 1;
			case unknown:
				return 2;
		}
		return 2;
	}

	protected void setValue(Object element, Object value) {
		Person person = (Person) element;
		int id = (Integer) value;
		switch (id) {
			case 0:
				person.setGender(Gender.male);
				break;
			case 1:
				person.setGender(Gender.female);
				break;
			case 2:
				person.setGender(Gender.unknown);
				break;
		}
		viewer.refresh();
	}
}
